package com.xinruke.hostels.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JwtUtil
 * @CreateDate 2019/6/16
 * @Author FengXinQiang
 * @Version V1.0.0.0
 * @Decription JSON Web Token
 */
public class JwtUtil {
    private static final long TIME_LIMIT = 1000 * 60 * 60 * 24;
    private static final String SECRET_KEY = "jwt@2019.hotel";
    /**
     * 预订系统登录类型
     */
    private static final String LOGIN_TYPE_RESERVATION = "reservation";
    /**
     * 业务管理系统登录类型
     */
    private static final String LOGIN_TYPE_MANAGE = "manage";

    /**
     * 从token中获取登录编号
     *
     * @param token
     * @return
     */
    public static String getLoginCode(String token) {
        return getTokenBody(token).getSubject();
    }

    /**
     * 判断是否预订系统登录
     *
     * @param token
     * @return
     */
    public static boolean isReservationLogin(String token) {
        String loginType = (String) getTokenBody(token).get(LOGIN_TYPE_RESERVATION);
        return LOGIN_TYPE_RESERVATION.equals(loginType);
    }

    /**
     * 判断是否业务管理系统登录
     *
     * @param token
     * @return
     */
    public static boolean isManageLogin(String token) {
        String loginType = (String) getTokenBody(token).get(LOGIN_TYPE_MANAGE);
        return LOGIN_TYPE_MANAGE.equals(loginType);
    }

    /**
     * 生成预订系统登录Token
     *
     * @param str
     * @param map
     * @return
     */
    public static String createReservationToken(String str, Map map) {
        return createToken(str, LOGIN_TYPE_RESERVATION, map);
    }

    /**
     * 生成业务管理系统登录Token
     *
     * @param str
     * @param map
     * @return
     */
    public static String createManageToken(String str, Map map) {
        return createToken(str, LOGIN_TYPE_MANAGE, map);
    }

    /**
     * 生成系统登录Token
     *
     * @param str
     * @param map
     * @return
     */
    private static String createToken(String str, String loginType, Map map) {
        String token = "";

        JwtBuilder builder = Jwts.builder().signWith(SignatureAlgorithm.HS512, SECRET_KEY);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(loginType, loginType);

        if (map != null) {
            paramMap.putAll(map);
        }
        token = builder.setClaims(paramMap).setIssuer("hostels").setSubject(str).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + TIME_LIMIT)).compact();

        return token;
    }

    private static Claims getTokenBody(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt).getBody();
        return claims;
    }

}
